﻿using Quartz;
using Quartz.Impl.Matchers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GrayParrot.Scheduling
{
    public class RunOnceTriggerListener : ITriggerListener
    {
        public const string GROUP_NAME = "@GP_RunOnceGroup$$";

        private Guid m_key = Guid.Empty;

        public RunOnceTriggerListener()
        {
            m_key = Guid.NewGuid();
        }

        public TriggerKey TriggerKey
        {
            get { return new TriggerKey(m_key.ToString(), RunOnceTriggerListener.GROUP_NAME); }
        }

        public KeyMatcher<TriggerKey> KeyMatcher
        {
            get { return KeyMatcher<TriggerKey>.KeyEquals(TriggerKey); }
        }

        public string Name
        {
            get { return TriggerKey.Name; }
        }

        public void TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode)
        {
            GrayParrot.Logging.Logger.For<RunOnceTriggerListener>().DebugFormat("Trigger:{0} for Job:{1} completed at {2}", trigger.Key, trigger.JobKey.Name, DateTime.Now);
        }

        public void TriggerFired(ITrigger trigger, IJobExecutionContext context)
        {
            // no action...
            GrayParrot.Logging.Logger.For<RunOnceTriggerListener>().DebugFormat("Trigger:{0} for Job:{1} fired at {2}", trigger.Key, trigger.JobKey.Name, DateTime.Now);
        }

        public void TriggerMisfired(ITrigger trigger)
        {
            // no action...
            GrayParrot.Logging.Logger.For<RunOnceTriggerListener>().DebugFormat("Trigger:{0} for Job:{1} Misfired at {2}", trigger.Key, trigger.JobKey.Name, DateTime.Now);
        }

        public bool VetoJobExecution(ITrigger trigger, IJobExecutionContext context)
        {
            // no vetos...
            GrayParrot.Logging.Logger.For<RunOnceTriggerListener>().DebugFormat("Veto for Trigger:{0} fro Job:{1} fired at {2}", trigger.Key, trigger.JobKey.Name, DateTime.Now);

            return false;
        }
    }
}
